<?php

namespace app\mp\controller;

use app\common\baidu\Trans;
use app\common\entity\BackResult;
use app\common\entity\Result;
use app\mp\service\MpUserService;
use app\Request;
use app\wxapp\service\UploadService;
use EasyWeChat\Factory;
use EasyWeChat\OfficialAccount\Application;
use think\facade\Db;
use app\common\youdao\Assess;


class Open
{
    /**
     * @var \EasyWeChat\OfficialAccount\Application
     */
    private $mpApp = null;

    public function mpinit()
    {
        $config = [
            'app_id' => 'wx9a9b89f8e9532671',
            'secret' => '09195eeb16c889e5cfcb2dd0db1018c5',
            'token' => 'doctorclass',
            'response_type' => 'array',
            //...
        ];
        //aesKey=TNgOR04Lx19Zsly3kgG3cWp37QaPu4qfzD5EVf4HR4u

        $this->mpApp = Factory::officialAccount($config);

    }

    public function trans()
    {
        $result = Trans::translate("hello", "en", 'zh');
        echo json_encode($result);
    }

    /**
     * 微信公众号对接地址
     */
    public function api()
    {
        $this->mpinit();
        $this->mpApp->server->push(function ($message) {

            Db::table("just_record")->insert([
                'content' => serialize($message),
                'create_time' => date("Y-m-d H:i:s")
            ]);
            return "您好！欢迎使用!" . $message['Content'];
        });
        $response = $this->mpApp->server->serve();
        // 将响应输出
        return $response->send();
    }

    public function auth(Request $request)
    {
        $this->mpinit();
        $url = "http://www.doctorsclass.com/mp/open/login/url/" . urlencode(str_replace('/', '-', base64_encode($request->header('referer'))));
        $url = $this->mpApp->oauth->scopes(['snsapi_userinfo'])->redirect($url);
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9a9b89f8e9532671&redirect_uri=http%3A%2F%2Fapi.doctorsclass.com%2F&response_type=code&scope=snsapi_userinfo&state=9f64a898807a159b68eb2d490511fe16&connect_redirect=1#wechat_redirect

        header('Location: ' . $url);
        exit;
//        $response->send();
//        exit;
    }

    public function login(Request $request)
    {
        $this->mpinit();
        $code = $request->param('code');
        $url = base64_decode(str_replace('-', '/', urldecode($request->param('url'))));
        $user = $this->mpApp->oauth->userFromCode($code);
        //$mpUser = json_encode($user,);

        $service = new MpUserService();
        $res = $service->login($user);

        // 生成一个token用于后期访问 如果是同一个域名 则可以用session
        echo <<<PAGE
<script type="text/javascript" >
        localStorage.setItem("token","{$res['token']}");
        window.location.href = "{$url}";
</script>
PAGE;
    }


    public function jssdk(Request $request)
    {
        $url = $request->header('referer');
        $this->mpinit();
        $apis = ["chooseImage", "closeWindow", "onMenuShareTimeline", "chooseWXPay", "startRecord", "stopRecord", "playVoice", "pauseVoice", "stopVoice", "onVoicePlayEnd", "uploadVoice", "downloadVoice"];
        $this->mpApp->jssdk->setUrl($url);
        $res = $this->mpApp->jssdk->buildConfig($apis, false, false, true);

        return BackResult::success(json_decode($res));
    }

    public function downloadVoice(Request $request)
    {
        $mediaId = $request->param("mediaId");
        $videoId = $request->param('videoId');
        $sentenceId = $request->param("sentenceId");
        $uid = $request->param("uid");

        if (empty($mediaId) || empty($videoId) || empty($sentenceId) || empty($uid)) {
            return Result::error("参数错误");
        }

        $this->mpinit();
        $accessToken = $this->mpApp->access_token->getToken();
        $accessToken = $accessToken['access_token'];
        $service = new UploadService();
        $data = $service->uploadVoiceColloquialMp($accessToken, $mediaId, $videoId, $sentenceId, $uid);
        return Result::success($data);

//        $access = new Assess();
//        $res = $access->doAssess($path,"hello");
    }

}

